
package com.tools.cleanmaster.ui.utils;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;

import com.tools.cleanmaster.common.thread.ThreadPool;
import com.tools.cleanmaster.utils.FeatureConfig;
import com.tools.cleanmaster.utils.LogHelper;

import java.util.ArrayList;

public class FeedBackUtils {

    /**
     * 发送反馈，成功发送或者保存反馈信息
     *
     * @param context
     * @param appName
     * @param appVersion
     * @param message
     * @throws Exception
     */
    public static void feedBackSuccessdOrRetained(Context context, String appName,
                                                  String appVersion, String message) {
        boolean success = false;// 反馈API DXApi.feedback(context, appName, appVersion, message, null);
        if (!success) {
            FeedBackDao dao = FeedBackDao.getInstance(context);
            dao.retain(appName, appVersion, message);
        }
    }

    /**
     * 将未发送的信息全部进行发送
     */
    public static void resendUnsuccessfulFeedBack(final Context context) {
        ThreadPool.runOnPool(new Runnable() {

            @Override
            public void run() {
                sendFeedbackAgain(context);
            }
        });

    }

    private static void sendFeedbackAgain(Context context) {
        FeedBackDao dao = FeedBackDao.getInstance(context);
        ArrayList<FeedBackContents> list = dao.queryAllRetainFeedbackRecords();
        if (list == null || list.size() == 0) {
            return;
        }

        LogHelper.i("FeedBackUtils", "FeedBack record size:" + list.size());

        try {
            for (FeedBackContents content : list) {
                boolean success = false;// 反馈API DXApi.feedback(context, content.app_name, content.app_version,
                if (success) {
                    dao.delete(content._id);
                }
            }
        } catch (Exception e) {

        }
    }

    static class FeedBackDao {
        static class FeedBackDBHelper extends SQLiteOpenHelper {
            private FeedBackDBHelper(Context context, String name, CursorFactory factory,
                                     int version) {
                super(context, name, factory, version);
            }

            @Override
            public void onCreate(SQLiteDatabase db) {
                db.execSQL(DROP_TABLE_IF_EXIST);
                db.execSQL(CREATE_TABLE_SQL);
            }

            @Override
            public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

            }
        }

        private static FeedBackDao sInstance = null;

        private FeedBackDao() {

        }

        public static FeedBackDao getInstance(Context context) {
            context = context.getApplicationContext();
            if (sInstance == null) {
                synchronized (context) {
                    if (sInstance == null) {
                        sInstance = new FeedBackDao();
                        sInstance.helper = new FeedBackDBHelper(context, DATABASE_NAME, null,
                                DB_VERSION);
                    }
                }
            }
            return sInstance;
        }

        public void retain(String appName, String appVersion, String message) {
            SQLiteDatabase db = null;
            try {
                db = helper.getWritableDatabase();

                if (db == null) {
                    return;
                }

                String sql = "INSERT INTO " + TABLE_NAME + " (" + "app_name" + "," + "app_version"
                        + "," + "message" + ")" + " values (?,?,?)";
                db.execSQL(sql, new Object[]{
                        appName, appVersion, message
                });
            } catch (SQLiteException e) {
                if (FeatureConfig.DEBUG_LOG) {
                    LogHelper.e("FeedBackUtils", "SQLiteDiskIOException:", e);
                }
            }
        }

        public ArrayList<FeedBackContents> queryAllRetainFeedbackRecords() {
            SQLiteDatabase db = null;
            Cursor cursor = null;
            ArrayList<FeedBackContents> list = null;
            try {
                db = helper.getReadableDatabase();

                if (db == null) {
                    return null;
                }

                list = new ArrayList<FeedBackContents>();
                cursor = db.query(TABLE_NAME, null, null, null, null, null, null);

                while (cursor.moveToNext()) {
                    FeedBackContents item = new FeedBackContents();
                    item._id = cursor.getInt(0);
                    item.app_name = cursor.getString(1);
                    item.app_version = cursor.getString(2);
                    item.message = cursor.getString(3);
                    list.add(item);
                }
            } catch (SQLiteException e) {
                if (FeatureConfig.DEBUG_LOG) {
                    LogHelper.e("FeedBackUtils", "SQLiteDiskIOException:", e);
                }
            } finally {
                if (cursor != null) {
                    cursor.close();
                }
            }
            return list;
        }

        public void delete(int index) {
            SQLiteDatabase db = null;
            try {
                db = helper.getWritableDatabase();

                if (db == null) {
                    return;
                }

                db.delete(TABLE_NAME, "_id = ?", new String[]{String.valueOf(index)});
            } catch (SQLiteException e) {
                if (FeatureConfig.DEBUG_LOG) {
                    LogHelper.e("FeedBackUtils", "SQLiteDiskIOException:", e);
                }
            }
        }

        private FeedBackDBHelper helper;

        public static final String TABLE_NAME = "Easy";

        public static final String DATABASE_NAME = "details";

        public static final int DB_VERSION = 1;

        public static final String DROP_TABLE_IF_EXIST = "DROP TABLE IF EXISTS " + TABLE_NAME + ";";

        public static final String CREATE_TABLE_SQL = "CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " ("
                + "_id INTEGER PRIMARY KEY AUTOINCREMENT, "
                + "app_name TEXT, "
                + "app_version TEXT, "
                + "message TEXT )";
    }

    static class FeedBackContents {
        int _id;
        String app_name;
        String app_version;
        String message;
    }
}
